﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Pool
{
    public string tag;
    public GameObject prefab;
    public int size;
}

public class ObjectPool : MonoBehaviour {

    public static ObjectPool Instance;
    public List<Pool> poolList = new List<Pool>();
    private Dictionary<string, Queue<GameObject>> poolDic = new Dictionary<string, Queue<GameObject>>();
	// Use this for initialization
	void Start () {
        Instance = this;
        InitPool();
	}

    private void InitPool()
    {
        foreach (Pool p in poolList)
        {
            Queue<GameObject> queue = new Queue<GameObject>();
            for (int i = 0; i < p.size; i++)
            {
                GameObject g = Instantiate(p.prefab,transform);
                g.SetActive(false);
                queue.Enqueue(g);
            }
            poolDic.Add(p.tag, queue);
        }
    }

    private void FillPool(string tag)
    {
        Pool tempPool = null;
        foreach (Pool p in poolList)
        {
            if (p.tag == tag)
            {
                tempPool = p;
                break;
            }
        }
        if (tempPool == null)
            return;
        for (int i = 0; i < tempPool.size; i++)
        {
            GameObject g = Instantiate(tempPool.prefab, transform);
            ReturnPool(tag, g);
        }
    }

    public void ReturnPool(string tag, GameObject g)
    {
        if (!poolDic.ContainsKey(tag))
            return;
        g.SetActive(false);
        poolDic[tag].Enqueue(g);
    }

    public GameObject GetFromPool(string tag)
    {
        if (!poolDic.ContainsKey(tag))
            return null;
        if (poolDic[tag].Count == 0)
        {
            FillPool(tag);
        }
        GameObject g = poolDic[tag].Dequeue();
        g.SetActive(true);
        return g;
    }
}
